var core = require('core');
var util = core.util;
var wechat = core.wechat;
var send = core.send;
var get = function(req, res, next){
    var query = req.query;
    var mid = query.mid;
    var state = query.state || null;
    var code = query.code;
    var SEND;
    var template = "pay";

    if(!state)
        return res.redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid="+wechat.config.AppID+"&redirect_uri="+ wechat.config.URL+"pay&response_type=code&scope=snsapi_base&state="+ mid +"#wechat_redirect");
    else{
        var param = {
            appid : wechat.config.AppID,
            secret : wechat.config.AppSecret,
            code : code,
            grant_type : 'authorization_code'
        };
        wechat.api.get('sns/oauth2/access_token', param, function(err, body){
            if(err || body.errmsg){
                SEND = new send(400000);
                SEND.docs = {
                    jssdk : wechat.getJSSDK(req.originalUrl)
                };
                template = "admin/error";
            }else{
                console.log(state,'==============无人货架');
                SEND = new send(0);
                SEND.docs = {
                    openid: body.openid,
                    mid: state,
                    jssdk: wechat.getJSSDK(req.originalUrl)
                };
            };

            return res.render(template, SEND);
        });
    };
};

module.exports = get;
